package com.ruoyi.common.utils;

import cn.hutool.extra.ssh.Sftp;
import com.ruoyi.common.config.FtpConfig;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;

/**
 * @author liuzhiqiang
 */
public class FtpUtils {

    public static FtpConfig ftpConfig;

    /**
     * 上传
     *
     * @param inputStream
     * @param fileName
     * @return
     */
    public static Boolean upload(InputStream inputStream, String fileName) {
        try {
            Sftp sftp = new Sftp(ftpConfig.getHost(), ftpConfig.getPort(), ftpConfig.getUsername(), ftpConfig.getPassword());
            String directory = ftpConfig.getRootDirectory() + ftpConfig.getPutDirectory();
            if (!sftp.isDir(directory)) {
                sftp.mkdir(directory);
            }
            sftp.upload(directory, fileName, inputStream);
            sftp.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static List<String> ls() {
        try {
            Sftp sftp = new Sftp(ftpConfig.getHost(), ftpConfig.getPort(), ftpConfig.getUsername(), ftpConfig.getPassword());
            String directory = ftpConfig.getRootDirectory() + ftpConfig.getGetDirectory();
            if (!sftp.isDir(directory)) {
                return null;
            }
            List<String> list = sftp.ls(directory);
            sftp.close();
            return list;
        } catch (Exception e) {
            return null;
        }
    }

    public static ByteArrayOutputStream get(String filePath) {
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            Sftp sftp = new Sftp(ftpConfig.getHost(), ftpConfig.getPort(), ftpConfig.getUsername(), ftpConfig.getPassword());
            String directory = ftpConfig.getRootDirectory() + ftpConfig.getGetDirectory();
            if (!sftp.isDir(directory)) {
                return null;
            }
            sftp.download(directory + "/" + filePath, byteArrayOutputStream);
            sftp.close();
            return byteArrayOutputStream;
        } catch (Exception e) {
            return null;
        }
    }

    public static void rm(String filePath) {
        try {
            Sftp sftp = new Sftp(ftpConfig.getHost(), ftpConfig.getPort(), ftpConfig.getUsername(), ftpConfig.getPassword());
            String directory = ftpConfig.getRootDirectory() + ftpConfig.getGetDirectory();
            if (sftp.isDir(directory)) {
                sftp.delFile(directory + "/" + filePath);
            }
            sftp.close();
        } catch (Exception e) {
        }
    }
}
